package com.wp.targetOffer;

import java.util.stream.IntStream;

/**
 * Created by 王萍 on 2017/8/1 0001.
 */
//给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
//解题方式：类似二分法求解，而不是循环一个一个的乘上去。
//多使用位运算，三目运算符。
public class 数值的整数次方 {

    public static void main(String[] args) {

        System.out.println(Power2(2, -3));
        IntStream.range(1, 10).forEach(x -> System.out.println(Power2(2, x)));
    }

    public static double Power(double base, int exponent) {

        double baseCopy = base;
        int absExponent = exponent;
        if (exponent == 0) return 1;
        else if (exponent < 0) absExponent = -exponent;

        int x = 1;
        while (x << 1 <= absExponent) {
            x <<= 1;
            base *= base;
        }
        if (absExponent > x) {
            base *= Power(baseCopy, absExponent - x);  //这里会递归。
        }
        return exponent<0?1.0/base:base;
    }

    public static double Power2(double base, int exponent) {

        int result = 1;
        int absExponent = exponent;
        if (exponent == 0) return 1;
        else if (exponent < 0) absExponent = -exponent;
        while (absExponent != 0) {
            if ((absExponent & 1) == 1) {
                result *= base;
            }
            base *= base;   //每移一位，base翻一倍。
            absExponent >>= 1;
        }
        return exponent < 0 ? 1.0 / result : result;
    }
}
